package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.constant.MessageConstant;
import com.hmdp.constant.RedisConstant;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.UUID;

@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryList() {
        String key = RedisConstant.SHOP_TYPE_KEY;
        //1.从redis查询商铺列表 以shop:type:加随机的UUID作为key
        String shopList = stringRedisTemplate.opsForValue().get(key);
        //2.存在 返回
        if (shopList != null && !shopList.isEmpty()) {
            List<ShopType> shopTypes = JSONUtil.toList(shopList, ShopType.class);
            return Result.ok(shopTypes); // 缓存存在，直接返回
        }
        //3.不存在 从数据库中查询 遍历集合
        List<ShopType> shopTypes = query().orderByAsc("sort").list();
        //4.不存在 报错
        if(shopTypes==null){
            return Result.fail(MessageConstant.SHOP_TYPE_NOT_EXIST);
        }
        //5.存在 写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopTypes));
        //6.返回结果
        return Result.ok(shopTypes);
    }
}
